package com.zbkj.crmeb.merchant.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.CommonPage;
import com.crmeb.core.common.CommonResult;
import com.common.PageParamRequest;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.utils.CrmebUtil;
import com.utils.DateUtil;
import com.utils.vo.dateLimitUtilVo;
import com.zbkj.crmeb.agent.model.Agent;
import com.zbkj.crmeb.agent.request.AdminAgentRequest;
import com.zbkj.crmeb.agent.response.AgentInfoResponse;
import com.zbkj.crmeb.agent.service.AgentService;
import com.zbkj.crmeb.chant.dao.ChannelMerchantDao;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.request.MerchantListRequest;
import com.zbkj.crmeb.chant.vo.ChannelMerchantVO;
import com.zbkj.crmeb.merchant.admin.service.MerAgentUserService;
import com.zbkj.crmeb.system.service.SystemAdminService;
import com.zbkj.crmeb.user.dao.UserDao;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.request.AgentUserRequest;
import com.zbkj.crmeb.user.response.UserResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 服务商-用户管理
 *
 * @author lvmd
 * @date 2022-02-18
 */
@Service
@Slf4j
public class MerAgentUserServiceImpl implements MerAgentUserService {

    @Resource
    private UserDao userDao;
    @Resource
    private SystemAdminService systemAdminService;
    @Resource
    private ChannelMerchantDao channelMerchantDao;
    @Resource
    private AgentService agentService;

    @Override
    public PageInfo<UserResponse> listAgentUsers(AgentUserRequest request, PageParamRequest pageParamRequest) {
        /*
        1.可以查看所属商户的所有用户，但是不能进行任何操作（1.不可以查看用户的手机号；2.无分组；3.只可以查看详情）
         */
        List<Integer> merIds = systemAdminService.getAdminAgentMerIds();
        if (CollectionUtils.isEmpty(merIds)) {
            return new PageInfo<>();
        }
        QueryWrapper<UserResponse> queryWrapper = new QueryWrapper<>();
        queryWrapper.groupBy("u.uid");
        if (request.getIsPromoter() != null) {
            queryWrapper.eq("u.is_promoter", request.getIsPromoter());
        }
        if (!StringUtils.isBlank(request.getGroupId())) {
            queryWrapper.apply(CrmebUtil.getFindInSetSql("u.group_id", request.getGroupId()));
        }
        if (null != request.getTagId()) {
            queryWrapper.apply(CrmebUtil.getFindInSetSql("u.tag_ids", request.getTagId()));
        }

        if (request.getConsumptionType() != null) {
//            queryWrapper.eq("u.mer_id",request.getMerId());
            switch (request.getConsumptionType()) {
                case 1:
                    queryWrapper.orderByDesc("consumptionPrice");
                    break;
                case 2:
                    queryWrapper.orderByDesc("consumptionNumber");
                    break;
                case 3:
                    queryWrapper.orderByDesc("recentConsumptionTime");
                    break;
                default:
                    throw new CrmebException("商家小程序筛选参数异常");
            }
        }
        if (StringUtils.isNotBlank(request.getPayCount())) {
            if (Integer.parseInt(request.getPayCount()) < 0) {
                queryWrapper.eq("u.pay_count", 0);
            } else {
                queryWrapper.gt("u.pay_count", request.getPayCount());
            }
        }

        if (!StringUtils.isBlank(request.getLevel())) {
            queryWrapper.in("u.level", CrmebUtil.stringToArray(request.getLevel()));
        }

        if (StringUtils.isNotBlank(request.getUserType())) {
            queryWrapper.eq("u.user_type", request.getUserType());
        }

        if (StringUtils.isNotBlank(request.getSex())) {
            queryWrapper.eq("u.sex", request.getSex());
        }
        if (StringUtils.isNotBlank(request.getCountry())) {
            queryWrapper.eq("u.country", request.getCountry());
        }
        if (request.getStatus() != null) {
            queryWrapper.eq("u.status", request.getStatus());
        }
        if (request.getMerId() != null) {
            queryWrapper.eq("u.mer_id", request.getMerId());
        }
        queryWrapper.in(CollectionUtils.isNotEmpty(merIds), "u.mer_id", merIds);

        dateLimitUtilVo dateLimit = DateUtil.getDateLimit(request.getData());

        if (!StringUtils.isBlank(dateLimit.getStartTime())) {
            switch (request.getAccessType()) {
                case 1:
                    queryWrapper.between("u.update_time", dateLimit.getStartTime(), dateLimit.getEndTime());
                    break;
                case 2:
                    queryWrapper.notBetween("u.update_time", dateLimit.getStartTime(), dateLimit.getEndTime());
                    break;
                case 3:
                    queryWrapper.apply(" and u.create_time = u.last_login_time");
                    break;
                default:
                    queryWrapper.between("u.create_time", dateLimit.getStartTime(), dateLimit.getEndTime());
                    break;
            }
        }
        if (request.getKeywords() != null) {
            String keywords = request.getKeywords();
            queryWrapper.and(i -> i.or().like("u.account", keywords) //用户账号
                    .or().like("u.real_name", keywords) //真实姓名
                    .or().like("u.card_id", keywords) //身份证号码
                    .or().like("u.mark", keywords) //用户备注
                    .or().like("u.phone", keywords) //手机号码
                    .or().like("u.add_ip", keywords) //创建IP
                    .or().like("u.last_ip", keywords) //最后一次登录ip
                    .or().like("u.addres", keywords) //详细地址
                    .or().like("u.nickname", keywords)); //用户昵称
        }
        if (StringUtils.isNotBlank(request.getSpreadKeyword())) {
            String spreadSql;
            if (request.getMerId() != null) {
                spreadSql = " u.spread_uid in (SELECT uid from eb_user where nickname like \"%" + request.getSpreadKeyword() + "%\" and mer_id = " + request.getMerId() + ")";
            } else {
                spreadSql = " u.spread_uid in (SELECT uid from eb_user where nickname like \"%" + request.getSpreadKeyword() + "%\")";
            }
            queryWrapper.apply(spreadSql);
        }
        if (request.getConsumptionType() == null) {
            queryWrapper.orderByDesc("u.uid");
        }

        Page<User> pageUser = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<User> userList = userDao.selectUserInfoList(queryWrapper);

//        List<Integer> merIds = userList.stream().map(User::getMerId).distinct().collect(Collectors.toList());
        List<ChannelMerchant> channelMerchants = channelMerchantDao.selectBatchIds(merIds);
        Map<Integer, String> merchantMap = channelMerchants.stream().collect(Collectors.toMap(ChannelMerchant::getId, ChannelMerchant::getChannelName));

        List<UserResponse> userResponses = new ArrayList<>();
        for (User user : userList) {
            UserResponse userResponse = new UserResponse();
            BeanUtils.copyProperties(user, userResponse);

            userResponse.setMerName(merchantMap.get(user.getMerId()));
//            if(null != user.getMerId()) {
//                ChannelMerchant channelMerchant = channelMerchantService.getById(user.getMerId());
//                if(null != channelMerchant) {
//                    userResponse.setMerName(channelMerchant.getChannelName());
//                } else {
//                    userResponse.setMerName("未知");
//                }
//            }

            //获取推广人信息
//            if(user.getSpreadUid() == 0){
//                userResponse.setSpreadNickname("无");
//            }else{
//                //todo: 有可能用户已经被删掉了, 想办法清理无效的推广人
//                User spUser = userDao.selectById(user.getSpreadUid());
//                if(spUser!=null){
//                    userResponse.setSpreadNickname(spUser.getNickname());
//                }
//            }

            // 隐藏手机号
            userResponse.setPhone("********");
            userResponses.add(userResponse);
        }

        return CommonPage.copyPageInfo(pageUser, userResponses);
    }

    /**
     * 服务商商户列表
     *
     * @param searchRequest    搜索条件
     * @param pageParamRequest 分页参数
     * @return
     */
    @Override
    public PageInfo<ChannelMerchantVO> listAgentMerchants(MerchantListRequest searchRequest, PageParamRequest pageParamRequest) {
        /*
        可以查看所属账号可以查看的所有的商户
         */
        MerchantListRequest request = new MerchantListRequest();
        List<Integer> merIds = systemAdminService.getAdminAgentMerIds();
        if (CollectionUtils.isEmpty(merIds)) {
            return new PageInfo<>();
        }
        request.setMerIds(merIds);

        Page<ChannelMerchant> pageMerchant = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        List<ChannelMerchantVO> channelMerchantList = channelMerchantDao.merchantList(request);

        return CommonPage.copyPageInfo(pageMerchant, channelMerchantList);
    }

    /**
     * 分页显示服务商
     *
     * @param request          搜索条件
     * @param pageParamRequest 分页参数
     * @return
     */
    @Override
    public PageInfo<AgentInfoResponse> listAgents(AgentUserRequest request, PageParamRequest pageParamRequest) {
        /*
        3.一级服务商可以查看二级服务商列表，也可以查看对应的二级服务商详情（不可修改）
         */
        // 一级服务商id
        Integer id = systemAdminService.getAdminAgentId();

        Page<User> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<Agent> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Agent::getParentId, id);
        lambdaQueryWrapper.eq(Agent::getIsDel, 0);
        List<Agent> agents = agentService.list(lambdaQueryWrapper);

        List<AgentInfoResponse> responses = new ArrayList<>();
        agents.forEach(agent -> {
            AgentInfoResponse response = new AgentInfoResponse();
            BeanUtils.copyProperties(agent, response);
            responses.add(response);
        });
        return CommonPage.copyPageInfo(page, responses);
    }

    /**
     * 服务商用户详情
     *
     * @param userId uid
     * @return
     */
    @Override
    public UserResponse getAgentUserDetail(Integer userId) {
        User user = userDao.selectById(userId);
        if (Objects.isNull(user)) {
            throw new CrmebException("当期用户不存在，请刷新后重试");
        }
        UserResponse userResponse = new UserResponse();
        BeanUtils.copyProperties(user, userResponse);
        return userResponse;
    }

    /**
     * 服务商商户详情
     *
     * @param merchantId 商户id
     * @return
     */
    @Override
    public ChannelMerchantVO getAgentMerchantDetail(Integer merchantId) {

        MerchantListRequest request = new MerchantListRequest();
        request.setMerId(merchantId);
        List<ChannelMerchantVO> channelMerchantList = channelMerchantDao.merchantList(request);
        if (CollectionUtils.isEmpty(channelMerchantList)) {
            throw new CrmebException("当前商户不存在，请刷新后重试");
        }
        return channelMerchantList.get(0);
    }

    /**
     * 服务商详情
     *
     * @param id 服务商id
     * @return
     */
    @Override
    public AgentInfoResponse getAgentDetail(Integer id) {
        Agent agent = agentService.getById(id);
        if (Objects.isNull(agent)) {
            throw new CrmebException("当前服务商不存在，请刷新后重试");
        }
        AgentInfoResponse agentInfoResponse = new AgentInfoResponse();
        BeanUtils.copyProperties(agent, agentInfoResponse);

        List<Integer> merIds = systemAdminService.getAdminAgentMerIds();
        if (CollectionUtils.isEmpty(merIds)) {
            throw new CrmebException("当前服务商无商户");
        }
        List<ChannelMerchant> channelMerchantList = channelMerchantDao.selectList(Wrappers.<ChannelMerchant>lambdaQuery()
                .in(ChannelMerchant::getId, merIds)
                .select(ChannelMerchant::getId, ChannelMerchant::getChannelName));
        agentInfoResponse.setMerList(channelMerchantList);
        return agentInfoResponse;
    }

    /**
     * 商户下拉列表
     *
     * @param request
     * @return
     */
    @Override
    public CommonResult<List<ChannelMerchant>> listChannelMerchants(AdminAgentRequest request) {
        List<Integer> merIds = systemAdminService.getAdminAgentMerIds();
        if (CollectionUtils.isEmpty(merIds)) {
            return CommonResult.success(new ArrayList<>());
        }
        List<ChannelMerchant> channelMerchantList = channelMerchantDao.selectList(Wrappers.<ChannelMerchant>lambdaQuery()
                .in(ChannelMerchant::getId, merIds)
                .select(ChannelMerchant::getId, ChannelMerchant::getChannelName));
        return CommonResult.success(channelMerchantList);
    }

    /**
     * 账户详情
     *
     * @param userId
     * @param type
     * @param pageParamRequest
     * @return
     */
    @Override
    public Object getInfoByCondition(Integer userId, int type, PageParamRequest pageParamRequest) {
        return null;
    }
}
